﻿using System; 
using System.Text;
using System.Collections.Generic; 
using System.Data;
using System.Data.SqlClient;
using ART.Data;
using ART.Common;
using ART.Model;
using ART.Cache;

namespace ART.BLL {
  //TBAdmin
 	public partial class B_TBAdmin
	{
   		
		public B_TBAdmin()
		{}
        #region __________基础方法__________
		/// <summary>
		/// 删除指定缓存
		/// </summary>
		public void ClearCache(string key)
		{
		    string CacheKey = "BLL/TBAdmin";
			if(!string.IsNullOrEmpty(key)){
			    CacheKey+="/"+key;
			}
			LRSCache.GetCacheService().RemoveObject(CacheKey);
		}
		/// <summary>
		/// 增加一条数据
		/// </summary>
		public int  Add(ART.Model.M_TBAdmin model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("insert into TBAdmin(");			
            strSql.Append("UserName,PassWord,PrUserName,RealName,Sex,TelPhone,Email,Description,AddDate,LastLoginIP,LastLoginTime,LastLogoutTime,LoginTimes,Locked,SuperTF,PowerList,RolesId");
			strSql.Append(") values (");
            strSql.Append("@UserName,@PassWord,@PrUserName,@RealName,@Sex,@TelPhone,@Email,@Description,@AddDate,@LastLoginIP,@LastLoginTime,@LastLogoutTime,@LoginTimes,@Locked,@SuperTF,@PowerList,@RolesId");            
            strSql.Append(") ");            
            strSql.Append(";select @@IDENTITY");	
			#region __________参数__________	
			SqlParameter[] parameters = {
			            new SqlParameter("@UserName", SqlDbType.NVarChar,50) ,            
                        new SqlParameter("@PassWord", SqlDbType.NVarChar,50) ,            
                        new SqlParameter("@PrUserName", SqlDbType.NVarChar,50) ,            
                        new SqlParameter("@RealName", SqlDbType.NVarChar,20) ,            
                        new SqlParameter("@Sex", SqlDbType.NVarChar,2) ,            
                        new SqlParameter("@TelPhone", SqlDbType.NVarChar,15) ,            
                        new SqlParameter("@Email", SqlDbType.NVarChar,50) ,            
                        new SqlParameter("@Description", SqlDbType.NVarChar,255) ,            
                        new SqlParameter("@AddDate", SqlDbType.DateTime) ,            
                        new SqlParameter("@LastLoginIP", SqlDbType.NVarChar,50) ,            
                        new SqlParameter("@LastLoginTime", SqlDbType.DateTime) ,            
                        new SqlParameter("@LastLogoutTime", SqlDbType.DateTime) ,            
                        new SqlParameter("@LoginTimes", SqlDbType.Int,4) ,            
                        new SqlParameter("@Locked", SqlDbType.TinyInt,1) ,            
                        new SqlParameter("@SuperTF", SqlDbType.NVarChar,10) ,            
                        new SqlParameter("@PowerList", SqlDbType.Bit) ,               
                        new SqlParameter("@RolesId", SqlDbType.Int,4)             
              
            };
			
			            
            parameters[0].Value = model.UserName;                        
            parameters[1].Value = model.PassWord;                        
            parameters[2].Value = model.PrUserName;                        
            parameters[3].Value = model.RealName;                        
            parameters[4].Value = model.Sex;                        
            parameters[5].Value = model.TelPhone;                        
            parameters[6].Value = model.Email;                        
            parameters[7].Value = model.Description;                        
            parameters[8].Value = model.AddDate;                        
            parameters[9].Value = model.LastLoginIP;                        
            parameters[10].Value = model.LastLoginTime;                        
            parameters[11].Value = model.LastLogoutTime;                        
            parameters[12].Value = model.LoginTimes;                        
            parameters[13].Value = model.Locked;                        
            parameters[14].Value = model.SuperTF;                        
            parameters[15].Value = model.PowerList;                        
            parameters[16].Value = model.RolesId;            			
            #endregion
			   
			object obj = SqlHelper.ExecScalar(strSql.ToString(),parameters);			
			if (obj == null)
			{
				return 0;
			}
			else
			{
				                    
            	return Convert.ToInt32(obj);
                                                                  
			}			   
            		
		}

		/// <summary>
		/// 更新一条数据
		/// </summary>
		public bool Update(ART.Model.M_TBAdmin model)
		{
		    StringBuilder strSql=new StringBuilder();
			#region __________语句__________
			strSql.Append("update TBAdmin set ");
			                                                
            strSql.Append(" UserName = @UserName , ");                                    
            strSql.Append(" PassWord = @PassWord , ");                                    
            strSql.Append(" PrUserName = @PrUserName , ");                                    
            strSql.Append(" RealName = @RealName , ");                                    
            strSql.Append(" Sex = @Sex , ");                                    
            strSql.Append(" TelPhone = @TelPhone , ");                                    
            strSql.Append(" Email = @Email , ");                                    
            strSql.Append(" Description = @Description , ");                                    
            strSql.Append(" AddDate = @AddDate , ");                                    
            strSql.Append(" LastLoginIP = @LastLoginIP , ");                                    
            strSql.Append(" LastLoginTime = @LastLoginTime , ");                                    
            strSql.Append(" LastLogoutTime = @LastLogoutTime , ");                                    
            strSql.Append(" LoginTimes = @LoginTimes , ");                                    
            strSql.Append(" Locked = @Locked , ");                                    
            strSql.Append(" SuperTF = @SuperTF , ");                                    
            strSql.Append(" PowerList = @PowerList , ");                                    
            strSql.Append(" RolesId = @RolesId  ");            			
			strSql.Append(" where ID=@ID ");
			
			#endregion	
			
			#region __________参数__________	
            SqlParameter[] parameters = {
			            new SqlParameter("@ID", SqlDbType.Int,4) ,            
                        new SqlParameter("@UserName", SqlDbType.NVarChar,50) ,            
                        new SqlParameter("@PassWord", SqlDbType.NVarChar,50) ,            
                        new SqlParameter("@PrUserName", SqlDbType.NVarChar,50) ,            
                        new SqlParameter("@RealName", SqlDbType.NVarChar,20) ,            
                        new SqlParameter("@Sex", SqlDbType.NVarChar,2) ,            
                        new SqlParameter("@TelPhone", SqlDbType.NVarChar,15) ,            
                        new SqlParameter("@Email", SqlDbType.NVarChar,50) ,            
                        new SqlParameter("@Description", SqlDbType.NVarChar,255) ,            
                        new SqlParameter("@AddDate", SqlDbType.DateTime) ,            
                        new SqlParameter("@LastLoginIP", SqlDbType.NVarChar,50) ,            
                        new SqlParameter("@LastLoginTime", SqlDbType.DateTime) ,            
                        new SqlParameter("@LastLogoutTime", SqlDbType.DateTime) ,            
                        new SqlParameter("@LoginTimes", SqlDbType.Int,4) ,            
                        new SqlParameter("@Locked", SqlDbType.TinyInt,1) ,            
                        new SqlParameter("@SuperTF", SqlDbType.Bit) ,            
                        new SqlParameter("@PowerList", SqlDbType.NText) ,            
                        new SqlParameter("@RolesId", SqlDbType.Int,4)             
              
            };
            			            
            parameters[0].Value = model.ID;                        
            parameters[1].Value = model.UserName;                        
            parameters[2].Value = model.PassWord;                        
            parameters[3].Value = model.PrUserName;                        
            parameters[4].Value = model.RealName;                        
            parameters[5].Value = model.Sex;                        
            parameters[6].Value = model.TelPhone;                        
            parameters[7].Value = model.Email;                        
            parameters[8].Value = model.Description;                        
            parameters[9].Value = model.AddDate;                        
            parameters[10].Value = model.LastLoginIP;                        
            parameters[11].Value = model.LastLoginTime;                        
            parameters[12].Value = model.LastLogoutTime;                        
            parameters[13].Value = model.LoginTimes;                        
            parameters[14].Value = model.Locked;                        
            parameters[15].Value = model.SuperTF;                        
            parameters[16].Value = model.PowerList;                        
            parameters[17].Value = model.RolesId;            			
            #endregion
			
            int rows=SqlHelper.ExecNonQuery(strSql.ToString(),parameters);
			if (rows > 0)
			{
			//string cachekey="info_"+ID;
			//ClearCache(cachekey);
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(int ID)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from TBAdmin ");
			strSql.Append(" where ID=@ID");
						SqlParameter[] parameters = {
					new SqlParameter("@ID", SqlDbType.Int,4)
			};
			parameters[0].Value = ID;

			int rows=SqlHelper.ExecNonQuery(strSql.ToString(),parameters);
			
			//string cachekey="info_"+ID;
			//ClearCache(cachekey);
			
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
				/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool DeleteList(string IDlist )
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from TBAdmin ");
			strSql.Append(" where ID in ("+IDlist + ")  ");
			int rows=SqlHelper.ExecNonQuery(strSql.ToString());
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		
		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public ART.Model.M_TBAdmin GetModel(int ID)
		{
			string CacheKey = "BLL/TBAdmin/info_" + ID;
			object objModel = LRSCache.GetCacheService().RetrieveObject(CacheKey);
			 if (objModel == null)
			 {
				StringBuilder strSql=new StringBuilder();
				strSql.Append("select * from TBAdmin ");
				strSql.Append(" where ID=@ID");
				
							SqlParameter[] parameters = {
					new SqlParameter("@ID", SqlDbType.Int,4)
			};
			parameters[0].Value = ID;

				
				ART.Model.M_TBAdmin model=new ART.Model.M_TBAdmin();
				DataSet ds=SqlHelper.ExecDataSet(strSql.ToString(),parameters);
				
				if(ds.Tables[0].Rows.Count>0)
				{
				    #region __________实体赋值__________
													if(ds.Tables[0].Rows[0]["ID"].ToString()!="")
				{
					model.ID=int.Parse(ds.Tables[0].Rows[0]["ID"].ToString());
				}
																																				model.UserName= ds.Tables[0].Rows[0]["UserName"].ToString();
																																model.PassWord= ds.Tables[0].Rows[0]["PassWord"].ToString();
																																model.PrUserName= ds.Tables[0].Rows[0]["PrUserName"].ToString();
																																model.RealName= ds.Tables[0].Rows[0]["RealName"].ToString();
																																model.Sex= ds.Tables[0].Rows[0]["Sex"].ToString();
																																model.TelPhone= ds.Tables[0].Rows[0]["TelPhone"].ToString();
																																model.Email= ds.Tables[0].Rows[0]["Email"].ToString();
																																model.Description= ds.Tables[0].Rows[0]["Description"].ToString();
																												if(ds.Tables[0].Rows[0]["AddDate"].ToString()!="")
				{
					model.AddDate=DateTime.Parse(ds.Tables[0].Rows[0]["AddDate"].ToString());
				}
																																				model.LastLoginIP= ds.Tables[0].Rows[0]["LastLoginIP"].ToString();
																												if(ds.Tables[0].Rows[0]["LastLoginTime"].ToString()!="")
				{
					model.LastLoginTime=DateTime.Parse(ds.Tables[0].Rows[0]["LastLoginTime"].ToString());
				}
																																if(ds.Tables[0].Rows[0]["LastLogoutTime"].ToString()!="")
				{
					model.LastLogoutTime=DateTime.Parse(ds.Tables[0].Rows[0]["LastLogoutTime"].ToString());
				}
																																if(ds.Tables[0].Rows[0]["LoginTimes"].ToString()!="")
				{
					model.LoginTimes=int.Parse(ds.Tables[0].Rows[0]["LoginTimes"].ToString());
				}
																																if(ds.Tables[0].Rows[0]["Locked"].ToString()!="")
				{
					model.Locked=int.Parse(ds.Tables[0].Rows[0]["Locked"].ToString());
				}
																																				model.SuperTF= Utils.StrToBool(ds.Tables[0].Rows[0]["SuperTF"].ToString(),false);
																																model.PowerList= ds.Tables[0].Rows[0]["PowerList"].ToString();
																												if(ds.Tables[0].Rows[0]["RolesId"].ToString()!="")
				{
					model.RolesId=int.Parse(ds.Tables[0].Rows[0]["RolesId"].ToString());
				}
																									
						
					#endregion
					
					LRSCache.GetCacheService().AddObject(CacheKey, model, 2*60*60);		
					return model;
				}
				else
				{
					return null;
				}

             }
             return (ART.Model.M_TBAdmin)objModel;
		}

		/// <summary>
		/// 获得数据列表
		/// </summary>
		public DataSet GetList(string strWhere)
		{
			return GetList(0,strWhere,"");
		}
		/// <summary>
		/// 获得前几行数据
		/// </summary>
		public DataSet GetList(int Top,string strWhere,string filedOrder)
		{
			return GetList(0,"*",strWhere,filedOrder);
		}
		/// <summary>
		/// 获得前几行数据
		/// </summary>
		public DataSet GetList(int Top,string FieldName,string strWhere,string filedOrder)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select ");
			if(Top>0)
			{
				strSql.Append(" top "+Top.ToString());
			}
			strSql.Append(" "+FieldName+" FROM TBAdmin ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			if(filedOrder.Trim()!="")
			{
				strSql.Append(" order by " + filedOrder);
			}
			return SqlHelper.ExecDataSet(strSql.ToString());
		}
#endregion

      #region __________自定义方法__________
        #region 属性
        public static int AId
        {
            get
            {
                int num = 0;
                int.TryParse(JCookie.GetCookie("adm", "Id"), out num);
                return num;
            }
        }
        public static string UserName
        {
            get
            {
                return JCookie.GetCookie("adm", "UserName");
            }
        }
        public static string RealName
        {
            get
            {
                return JCookie.GetCookie("adm", "RealName");
            }
        }
        public static string LastLoginIP
        {
            get
            {
                return JCookie.GetCookie("adm", "LastLoginIP");
            }
        }
        public static string LastLoginTime
        {
            get
            {
                return JCookie.GetCookie("adm", "LastLoginTime");
            }
        }
        public static int LoginTimes
        {
            get
            {
                int num = 0;
                int.TryParse(JCookie.GetCookie("adm", "LoginTimes"), out num);
                return num;
            }
        }
        public static bool SuperTF
        {
            get
            {
                bool flag = false;
                bool.TryParse(JCookie.GetCookie("adm", "SuperTF"), out flag);
                return flag;
            }
        }
        public static int RolesId
        {
            get
            {
                int num = 0;
                int.TryParse(JCookie.GetCookie("adm", "RolesId"), out num);
                return num;
            }
        }
        public static string RolesName
        {
            get
            {
                return JCookie.GetCookie("adm", "RolesName");
            }
        }
        public static string PowerList
        {
            get
            {
                return JCookie.GetCookie("adm", "PowerList");
            }
        }
        #endregion
        public static int CheckLogin()
        {
            if (AId == 0)
            {
                return -1;
            }
            return 0;
        }
        public static void IsLogin()
        {
            if (AId == 0)
            {
                System.Web.HttpContext.Current.Response.Write("<script>window.top.location.href='/Admini/login.aspx'</script>");
            }
        }
        public void UpdateStatus(int _EmploeeId, int status)
        {
            string cmdText = string.Format("update TBAdmin SET Locked={0} WHERE Id={1}", status, _EmploeeId);
            SqlHelper.ExecNonQuery(cmdText, new SqlParameter[0]);
        }
        public void UpdateLoginStatus(int _EmploeeId)
        {
            string cmdText = string.Format("update TBAdmin SET LastLoginIP='{0}',LastLoginTime='{1}',LoginTimes=LoginTimes+1 WHERE Id={2}", LYRequest.GetIP(), DateTime.Now.ToString(), _EmploeeId);
            SqlHelper.ExecNonQuery(cmdText, new SqlParameter[0]);
        }
        public Model.M_TBAdmin GetModel(string Account, string PWD)
        {
            string CacheKey = "BLL/TBAdmin/iapws/" + Account;
            object objModel = LRSCache.GetCacheService().RetrieveObject(CacheKey);
            if (objModel == null)
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("select * from TBAdmin ");
                strSql.Append(" where UserName=@Account and PassWord=@PWD");

                SqlParameter[] parameters = {
					new SqlParameter("@Account", SqlDbType.VarChar, 50), 
                    new SqlParameter("@PWD", SqlDbType.VarChar, 64)
			};
                parameters[0].Value = Account;
                parameters[1].Value = PWD;

                ART.Model.M_TBAdmin model = new ART.Model.M_TBAdmin();
                DataSet ds = SqlHelper.ExecDataSet(strSql.ToString(), parameters);

                if (ds.Tables[0].Rows.Count > 0)
                {
                    #region __________实体赋值__________
                    if (ds.Tables[0].Rows[0]["ID"].ToString() != "")
                    {
                        model.ID = int.Parse(ds.Tables[0].Rows[0]["ID"].ToString());
                    }
                    model.UserName = ds.Tables[0].Rows[0]["UserName"].ToString();
                    model.PassWord = ds.Tables[0].Rows[0]["PassWord"].ToString();
                    model.PrUserName = ds.Tables[0].Rows[0]["PrUserName"].ToString();
                    model.RealName = ds.Tables[0].Rows[0]["RealName"].ToString();
                    model.Sex = ds.Tables[0].Rows[0]["Sex"].ToString();
                    model.TelPhone = ds.Tables[0].Rows[0]["TelPhone"].ToString();
                    model.Email = ds.Tables[0].Rows[0]["Email"].ToString();
                    model.Description = ds.Tables[0].Rows[0]["Description"].ToString();
                    if (ds.Tables[0].Rows[0]["AddDate"].ToString() != "")
                    {
                        model.AddDate = DateTime.Parse(ds.Tables[0].Rows[0]["AddDate"].ToString());
                    }
                    model.LastLoginIP = ds.Tables[0].Rows[0]["LastLoginIP"].ToString();
                    if (ds.Tables[0].Rows[0]["LastLoginTime"].ToString() != "")
                    {
                        model.LastLoginTime = DateTime.Parse(ds.Tables[0].Rows[0]["LastLoginTime"].ToString());
                    }
                    if (ds.Tables[0].Rows[0]["LastLogoutTime"].ToString() != "")
                    {
                        model.LastLogoutTime = DateTime.Parse(ds.Tables[0].Rows[0]["LastLogoutTime"].ToString());
                    }
                    if (ds.Tables[0].Rows[0]["LoginTimes"].ToString() != "")
                    {
                        model.LoginTimes = int.Parse(ds.Tables[0].Rows[0]["LoginTimes"].ToString());
                    }
                    if (ds.Tables[0].Rows[0]["Locked"].ToString() != "")
                    {
                        model.Locked = int.Parse(ds.Tables[0].Rows[0]["Locked"].ToString());
                    }
                    model.SuperTF = Utils.StrToBool(ds.Tables[0].Rows[0]["SuperTF"].ToString(), false);
                    model.PowerList = ds.Tables[0].Rows[0]["PowerList"].ToString();
                    if (ds.Tables[0].Rows[0]["RolesId"].ToString() != "")
                    {
                        model.RolesId = int.Parse(ds.Tables[0].Rows[0]["RolesId"].ToString());
                    }


                    #endregion

                    LRSCache.GetCacheService().AddObject(CacheKey, model, 2 * 60 * 60);
                    return model;
                }
                else
                {
                    return null;
                }

            }
            return (ART.Model.M_TBAdmin)objModel;
        }
        public bool IsAccountExist(string Account)
        {
            string cacheKey = "select count(*) from TBAdmin where UserName=@Account";
            SqlParameter[] cachedParameters = SqlHelper.GetCachedParameters(cacheKey);
            if (cachedParameters == null)
            {
                cachedParameters = new SqlParameter[] { new SqlParameter("@Account", SqlDbType.VarChar, 50) };
                cachedParameters[0].Value = Account;
            }
            object obj2 = SqlHelper.ExecScalar(cacheKey, null, cachedParameters);
            if (obj2 != null && obj2.ToString() != "0")
            {
                return true;
            }

            return false;
        }
        public static int Logout()
        {
            JCookie.WriteCookie("adm", "Id", "0", -1);
            return 1;
        }
        public static int Logined(string Account, string PWD)
        {
            int num = -1;
            if (Utils.NetLinked)
            {
                M_TBAdmin employees = new B_TBAdmin().GetModel(Account, PWD);
                if (employees == null || employees.ID == 0)
                {
                    return num;
                }
                if (employees.Locked != 1)
                {
                    num = 1;
                    JCookie.WriteCookie("adm", "Id", employees.ID.ToString(), 0.5);
                    JCookie.WriteCookie("adm", "UserName", employees.UserName.ToString(), 0.5);
                    JCookie.WriteCookie("adm", "RealName", employees.RealName.ToString(), 0.5);
                    JCookie.WriteCookie("adm", "LastLoginIP", employees.LastLoginIP.ToString(), 0.5);
                    JCookie.WriteCookie("adm", "LastLoginTime", employees.LastLoginTime.ToString(), 0.5);
                    JCookie.WriteCookie("adm", "LoginTimes", employees.LoginTimes.ToString(), 0.5);
                    JCookie.WriteCookie("adm", "SuperTF", employees.SuperTF.ToString(), 0.5);
                    JCookie.WriteCookie("adm", "RolesId", employees.RolesId.ToString(), 0.5);
                    string powerlist = "";
                    M_Roles mog = new B_Roles().GetModel(employees.RolesId);
                    if (mog != null)
                    {
                        JCookie.WriteCookie("adm", "RolesName", mog.RoleName.ToString(), 0.5);
                        powerlist = mog.PermissionsIds;
                    }
                    if (employees.PowerList != "") powerlist = employees.PowerList + "," + powerlist;
                    JCookie.WriteCookie("adm", "PowerList", powerlist, 0.5);
                    new B_TBAdmin().UpdateLoginStatus(employees.ID);
                    return num;
                }
                return 0;
            }
            return 3;
        }
        /// <summary>
        /// 检查是否有 指定权限
        /// </summary>
        /// <param name="PermissionsId"></param>
        /// <returns></returns>
        public static bool IsPermissions(int PermissionsId)
        {
            if (SuperTF)
            {
                return true;
            }
            if (Array.IndexOf<string>(PowerList.Trim(new char[] { ',' }).Split(new char[] { ',' }), PermissionsId.ToString()) <= -1)
            {
                return false;
            }
            return true;
        }
      #endregion 
	}
}

